package com.hspedu.hspliving.commodity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hspedu.hspliving.commodity.entity.BrandEntity;
import com.hspedu.hspliving.commodity.service.BrandService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hspedu.common.utils.PageUtils;
import com.hspedu.common.utils.Query;

import com.hspedu.hspliving.commodity.dao.CategoryBrandRelationDao;
import com.hspedu.hspliving.commodity.entity.CategoryBrandRelationEntity;
import com.hspedu.hspliving.commodity.service.CategoryBrandRelationService;

import javax.annotation.Resource;


@Service("categoryBrandRelationService")
public class CategoryBrandRelationServiceImpl extends ServiceImpl<CategoryBrandRelationDao, CategoryBrandRelationEntity> implements CategoryBrandRelationService {

    @Resource
    CategoryBrandRelationDao relationDao;
    @Resource
    BrandService brandService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryBrandRelationEntity> page = this.page(
                new Query<CategoryBrandRelationEntity>().getPage(params),
                new QueryWrapper<CategoryBrandRelationEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryBrandRelationEntity> queryByBrandId(Long brandId){
        LambdaQueryWrapper<CategoryBrandRelationEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CategoryBrandRelationEntity::getBrandId,brandId);
        List<CategoryBrandRelationEntity> categoryBrandRelationEntities =
                baseMapper.selectList(queryWrapper);
        return categoryBrandRelationEntities;
    }

    /**
     * 得到传入 分类id 对应的品牌信息
     * @param catId
     * @return
     */
    @Override
    public List<BrandEntity> getBrandsByCatId(Long catId) {
        //查找catId 关联的所有品牌
        List<CategoryBrandRelationEntity> categoryBrandRelationEntities
                = relationDao.selectList
                (new QueryWrapper<CategoryBrandRelationEntity>().eq("category_id",
                        catId));
        //这里是一个一个sql 语句发的，也可以收集到所有brandId, 一次查出返回(后面优化)
        List<BrandEntity> brandEntities =
                categoryBrandRelationEntities.stream().map(item -> {
                    Long brandId = item.getBrandId();
                    BrandEntity byId = brandService.getById(brandId);
                    return byId;
                }).collect(Collectors.toList());
        return brandEntities;
    }


}
